import axios from 'axios'
import {useAuthStore} from "@/stores/auth.js";


const service = axios.create({
    baseURL: import.meta.env.VITE_API_BASE_URL,
    timeout: 10000
})

// 请求拦截器
service.interceptors.request.use(config => {
    const authStore = useAuthStore()

    // 如果存在 token，添加到请求头
    if (authStore.token) {
        config.headers.Authorization = `Bearer ${authStore.token}`
    }
    // 如果是表单数据，自动设置 Content-Type
    if (config.data instanceof FormData) {
        config.headers['Content-Type'] = 'multipart/form-data'
    }
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
    response => {
        const {status, data} = response

        if (status >= 200 && status < 300) {
            return {
                success: true,
                httpCode: status,
                code: data.code,
                message: data.message,
                data: data.data
            }
        }

        return {
            success: false,
            httpCode: status,
            message: `HTTP Error: ${status}`,
            data: null
        }
    },
    error => {
        const status = error.response?.status || 0
        return {
            success: false,
            httpCode: status,
            message: error.message || 'Network Error',
            data: null
        }
    }
)

/**
 * 基础请求方法
 * @template T
 * @param {import('axios').AxiosRequestConfig} config
 * @returns {Promise<ApiResponse<T>>}
 */
export function request(config) {
    return service(config)
}

/**
 * GET请求快捷方法
 * @template T
 * @param {string} url
 * @param {Object} [params]
 * @returns {Promise<ApiResponse<T>>}
 */
export function get(url, params) {
    return request({url, method: 'get', params})
}

/**
 * POST请求快捷方法
 * @template T
 * @param {string} url
 * @param {Object} [data]
 * @param {import('axios').AxiosRequestConfig} [config]
 * @returns {Promise<ApiResponse<T>>}
 */
export function post(url, data, config) {
    return request({url, method: 'post', data, ...config})
}

export default service